var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

require("./dataBase/contact.js")



var indexRouter = require('./routes/index');
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var adminRouter = require("./routes/admin");
var orderRouter = require("./routes/order");
var goodsTypeRouter = require("./routes/goodsType");
var adRouter=require('./routes/ads');
var articalRouter = require('./routes/artical')
const goodsRouter=require('./routes/goods');
var filesRouter = require('./routes/files');
const session=require("express-session");
const FileStore=require("session-file-store")(session);


var app = express();

// CORS：设置允许跨域中间件
var allowCrossDomain = function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
};
app.use(allowCrossDomain); // 使用该中间件

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//设置cookie保存的配置信息
app.use(session({
  name:"currentUser",//自定义
  secret:"secret",
  store:new FileStore(),
  saveUninitialized:false,
  resave:false,
  cookie:{
    maxAge:1000*60*60//保存时间以毫秒为单位
  }
}))


app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/admin",adminRouter);
app.use("/order", orderRouter);
app.use("/goodsType", goodsTypeRouter);
app.use("/ads", adRouter);
app.use('/artical',articalRouter)


app.use('/files', filesRouter);
app.use('/goods', goodsRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
app.listen(3000, () => {
  console.log("服务器启动成功");
})
